/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.common.codec;

/**
 * 16进制编码转换
 *
 * @author vacoor
 */
@SuppressWarnings({"unused"})
public abstract class Hex {
    private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final int SHIFT = 4;
    private static final int MASK = (1 << SHIFT) - 1;

    /**
     * 将 byte 数组转换为 十六进制 形式
     *
     * @param bytes
     * @return
     */
    public static String encode(byte[] bytes) {
        return encode(bytes, 0, bytes.length);
    }

    public static String encode(byte[] bytes, int offset, int length) {
        StringBuilder hex = new StringBuilder(length << 1);

        for (int i = offset; i < offset + length; i++) {
            byte b = bytes[i];
            hex.append(DIGITS[(b >>> SHIFT) & MASK]).append(DIGITS[b & MASK]);
        }

        return hex.toString();
    }

    /**
     * 将 16进制字符串 转换为 byte[]
     *
     * @param hex
     * @return
     */
    public static byte[] decode(String hex) {
        return decode(hex.toCharArray());
    }

    public static byte[] decode(char[] hex) {
        int len = hex.length;
        if (0 != (len & 1)) {
            throw new IllegalArgumentException("Hex must be exactly two digits per byte.");
        }
        byte[] bytes = new byte[len >> 1];
        for (int i = 0, j = 0; i < bytes.length; i++) {
            int h = toDigit(hex[j++]) << 4;
            int l = toDigit(hex[j++]);
            bytes[i] = (byte) ((h | l) & 0xFF);
        }
        return bytes;
    }

    /**
     * 将16进制字符转换为整数
     */
    protected static int toDigit(char c) {
        return Character.digit(c, 16);
    }

    private Hex() {
    }
}

